package com.qfedu.web.servlet;

import com.alibaba.druid.util.StringUtils;
import com.qfedu.entity.PageBean;
import com.qfedu.pojo.Goods;
import com.qfedu.service.GoodsService;
import com.qfedu.service.impl.GoodsServiceImpl;
import com.qfedu.web.common.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * 创建者: QF-SUN
 * 创建时间: 2023/4/4 10:09
 * 描述:
 */
@WebServlet("/goodsservlet")
public class GoodsServlet extends BaseServlet {

    GoodsService goodsService = new GoodsServiceImpl();

    /**
     * 根据分类id查询 商品列表
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
    protected String getGoodsListByTypeId(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PageBean<Goods> pageBean ;
        //获取分类id
        String typeId = req.getParameter("typeId");
        String pageSizeStr = req.getParameter("pageSize");
        String pageNumStr = req.getParameter("pageNum");

        int pageSize = 2;
        int pageNum = 1; //设置默认值， 如果前端传参了， 则转换为int类型
        if(!StringUtils.isEmpty(pageNumStr)) {
            pageNum = Integer.parseInt(pageNumStr);
        }
        if(!StringUtils.isEmpty(pageSizeStr)) {
            pageSize = Integer.parseInt(pageSizeStr);
        }

        if(StringUtils.isEmpty(typeId)) {
            pageBean = new PageBean<>();
            pageBean.setTotalCount(0);
            pageBean.setPageNum(pageNum);
            pageBean.setPageSize(pageSize);
            pageBean.setData(new ArrayList<>());
        } else {
            pageBean = goodsService.findByPage(pageSize, pageNum , typeId);
        }
        //存储到请求域
        req.setAttribute("typeId", typeId);
        req.setAttribute("pageBean", pageBean );

        return "forward:/goodsList.jsp";
    }


    protected String getGoodsById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String goodsId = req.getParameter("id");
        Goods goods = goodsService.findById(Integer.parseInt(goodsId));

        req.setAttribute("goods", goods);
        return "forward:/goodsDetail.jsp";
    }

}
